package com.kantboot.business.talent.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.kantboot.business.talent.repository.*;
import com.kantboot.business.talent.service.IBusTalentUserAccountControllerInTalentService;
import com.kantboot.user.account.domain.entity.UserAccount;
import com.kantboot.user.account.repostiroy.UserAccountRepository;
import com.kantboot.user.account.service.IUserAccountService;
import com.kantboot.util.common.exception.BaseException;
import com.kantboot.util.core.redis.RedisUtil;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserAccountControllerInTalentServiceImpl implements IBusTalentUserAccountControllerInTalentService {

    @Resource
    private UserAccountRepository repository;

    @Resource
    private BusTalentUserAccountRepository userAccountRepository01;


    @Resource
    private RedisUtil redisUtil;

    @Resource
    private IUserAccountService userAccountService;

    @Resource
    private BusTalentEduMajorDegreeOfUserAccountRepository busTalentEduMajorDegreeOfUserAccountRepository;

    @Resource
    private BusTalentSeriesWorkExperienceOfUserAccountRepository busTalentSeriesWorkExperienceOfUserAccountRepository;

    @Resource
    private BusTalentAwardOfUserAccountRepository busTalentAwardOfUserAccountRepository;

    @Resource
    private BusTalentPlanOfUserAccountRepository busTalentPlanOfUserAccountRepository;

    @Resource
    private BusTalentPerformanceOfUserAccountRepository busTalentPerformanceOfUserAccountRepository;

    @Resource
    private BusTalentSkillLevelExperienceOfUserAccountRepository busTalentSkillLevelExperienceOfUserAccountRepository;

    @Resource
    private BusTalentTitleLevelExperienceOfUserAccountRepository busTalentTitleLevelExperienceOfUserAccountRepository;

    @Resource
    private BusTalentExpertLevelExperienceOfUserAccountRepository busTalentExpertLevelExperienceOfUserAccountRepository;


    /**
     * 判断是否未新增用户
     */
    private boolean isNew(UserAccount userAccount) {
        if (userAccount.getId() == null) {
            return true;
        }
        return !repository.existsById(userAccount.getId());
    }

    /**
     * 保存之前的校验
     */
    private UserAccount saveBeforeCheck(UserAccount userAccount) {
        if (isNew(userAccount)) {
            // 检测手机号是否重复
            UserAccount byPhoneAreaCodeAndPhone = repository.findByPhoneAreaCodeAndPhone(userAccount.getPhoneAreaCode(), userAccount.getPhone());
            if (byPhoneAreaCodeAndPhone != null) {
                throw BaseException.of("phoneRepeat", "手机号重复");
            }
            return userAccount;
        }
        Optional<UserAccount> byId = repository.findById(userAccount.getId());
        // 断言byId不会为空
        assert byId.isPresent();
        UserAccount userAccount1 = byId.get();
        // 如果手机号不为空，而且与原先的不一样，这个国网也不会有国外手机号，就不检测国际区号（phoneAreaCode）
        if (userAccount.getPhone() != null && (!userAccount.getPhone().equals(userAccount1.getPhone()))) {
            // 检测手机号是否重复
            UserAccount byPhoneAreaCodeAndPhone1 = repository.findByPhoneAreaCodeAndPhone(userAccount.getPhoneAreaCode(), userAccount.getPhone());
            if (byPhoneAreaCodeAndPhone1 != null) {
                throw BaseException.of("phoneRepeat", "手机号重复");
            }
        }
        return userAccount1;
    }


    /**
     * 保存用户账户信息
     * 该方法不仅保存用户账户信息，还同步保存与用户账户关联的人才相关信息，如奖项、计划、绩效和工作经历等
     *
     * @param userAccount 待保存的用户账户信息
     * @return 保存后的用户账户信息
     */
    @SneakyThrows
    @Override
    public UserAccount save(UserAccount userAccount) {
        // 删除redis
        redisUtil.delete("userAccountInTalent");
        // 保存之前的校验
        UserAccount userAccountBefore=saveBeforeCheck(userAccount);
        // 获取一个新的userAccount
        UserAccount userAccountNew = BeanUtil.copyProperties(userAccount, UserAccount.class);
        // 保存用户账户信息
        return repository.save(userAccountNew);
    }

    @Override
    public UserAccount saveSelf(UserAccount userAccount) {
        // 删除redis
        redisUtil.delete("userAccountInTalent");
        // 获取自身信息的ID
        Long selfId = userAccountService.getSelfId();
        userAccount.setId(selfId);
        return save(userAccount);
    }

    @Override
    public List<UserAccount> getAll() {
        // 查询redis缓存
        String jsonStr = redisUtil.get("userAccountInTalent");
        if (jsonStr != null) {
            return JSON.parseArray(jsonStr, UserAccount.class);
        }
        List<UserAccount> all = repository.findAll();
        redisUtil.set("userAccountInTalent", JSON.toJSONString(all));
        return all;
    }
}
